package com.boruan.shengtangfeng.core.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import com.boruan.shengtangfeng.core.utils.CommonEnum;
import com.boruan.shengtangfeng.core.utils.EnumUtil;

public final class StringToEnumConverterFactory implements ConverterFactory<String, CommonEnum> {

    @Override
    @SuppressWarnings("unchecked")
    public <T extends CommonEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends Enum<T> & CommonEnum> implements Converter<String, T> {

        private final Class<T> enumType;

        StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            source = source.trim();// 去除首尾空白字符
            return source.isEmpty() ? null : EnumUtil.getEnumByValue(this.enumType,Integer.parseInt(source));
        }
    }

}